package com.bren.android.androidproject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;


public class ScheduleActivity extends ListActivity{
	static final int MAX_EVENTS=35;
	static final int MAX_DAILY_EVENTS=5;
	static final int DAY_PICKER=0;
	static final int HOUR_PICKER=1;
	static final int MINUTE_PICKER=2;
	static final int FHOUR_PICKER=3;
	static final int FMINUTE_PICKER=4;
	static final int DELETE_CONFIRM=5;
	ContentValues cv=new ContentValues(3);
	String day, hour, minute, startHr, startMin, finishHr, finishMin;
	final CharSequence[] days={"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
	final CharSequence[] hours={"09:00","10:00","11:00","12:00","13:00","14:00","15:00","16:00","17:00","18:00",
								"19:00","20:00","21:00","22:00","23:00",
								"24:00","01:00","02:00","03:00","04:00","05:00","06:00","07:00","08:00"};
	final int[] hourValues={900,1000,1100,1200,1300,1400,1500,1600,1700,1800,
			1900,2000,2100,2200,2300,2400,100,200,300,400,500,600,700,800};
	final CharSequence[] minutes={"00","15","30","45"};
	final int[] minuteValues={0,15,30,45};
	int hourValue, minuteValue;
	SQLiteDatabase db=null;
	int pos;
	long rId;
	Cursor result=null;
	String deleteDay;
	int deleteStart, deleteFinish;
	BroadcastReceiver scheduleEvent;
	
	public void onCreate(Bundle savedInstance){
		super.onCreate(savedInstance);
		setContentView(R.layout.main3);
		
		startDb();
		
		Button btn=(Button)findViewById(R.id.addbutton);
		btn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(DAY_PICKER);// start chain of dialogs	
			}
		});
		btn.setEnabled(true);			
	}
	
	protected void startDb() {
		try {
			db=(new Database(this).getWritableDatabase());// this=getContext()
			android.util.Log.w("APActivity3", "Database open");
		} catch (SQLiteException e) {
			android.util.Log.e("APActiveiy3","Cannot open database");
		}	
		//db.execSQL("DELETE FROM schedule"); // used to clear database completely
	}
	
	protected void stopDb() {
		try {
			if(result!=null) {
				if(!result.isClosed()) {
					result.close();
				}	
				result=null;
			}
			if(db!=null) {
				if(db.isOpen()) {
					db.close();
				}
				db=null;
			}
			android.util.Log.w("APActivity3","Database closed");
		}catch (SQLiteException e) {
			android.util.Log.e("APActivity3","Cannot close database");
		}
	}
	
	public void onResume() {
		super.onResume();
		updateUI();
	}
	
	protected void onDestroy() {
		super.onDestroy();
		stopDb();
	}
	
	public void updateUI() {
		result=db.rawQuery("SELECT * FROM schedule", null);
		ListAdapter adapter=new SimpleCursorAdapter(this,
				R.layout.row, result, new String[] {"day","start","finish"},
				new int[] {R.id.day,R.id.start,R.id.finish});
		setListAdapter(adapter);
	    getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);    
	}
	
	public void onListItemClick(ListView parent, View v, int position, long id) {
		// need to display sorted list
		// access sorted list find values and delete from position in db
		// position in sorted list and db not same
		android.util.Log.w("List","Item clicked");
		result=db.rawQuery("SELECT * FROM schedule", null);
		result.moveToPosition(position);
		deleteDay = result.getString(1);
		deleteStart=result.getInt(2);
		deleteFinish=result.getInt(3);
		android.util.Log.w("positon:", String.valueOf(position));
		android.util.Log.w("Delete:", deleteDay);
		android.util.Log.w("Delete: ", String.valueOf(deleteStart));
		android.util.Log.w("Delete", String.valueOf(deleteFinish));
		pos=position;
		rId=id;
		showDialog(DELETE_CONFIRM);	
	}
	
	protected Dialog onCreateDialog(int id) {
		AlertDialog alert;
		AlertDialog.Builder builder=new AlertDialog.Builder(ScheduleActivity.this);
		
		switch (id) {
		case	DAY_PICKER:
			day=(String)days[0];//default to Monday
			builder.setTitle("Choose Day");
			builder.setCancelable(false);
			builder.setSingleChoiceItems(days, 0, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int item) {
					day=(String) days[item];
					android.util.Log.w("picker: ", day);
				}
			})
			.setPositiveButton("Set", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					cv.put("day", day);
					android.util.Log.w("picker: ", day);
					removeDialog(DAY_PICKER);
					showDialog(HOUR_PICKER);	
				}
			})
			.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					removeDialog(DAY_PICKER);
					dialog.cancel();
				}
			});
			break;
		case	HOUR_PICKER:
			hour=(String)hours[0];//default to 09:00
			hourValue=hourValues[0];
			builder.setTitle("Choose Start Hour");
			builder.setCancelable(false);
			builder.setSingleChoiceItems(hours, 0, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int item) {
					hour=(String) hours[item];
					hourValue=hourValues[item];
					hour=String.valueOf(hourValue);
					android.util.Log.w("picker: ", hour);	
				}
			})
			.setPositiveButton("Set", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					hour=String.valueOf(hourValue);
					android.util.Log.w("picker: ", hour);
					removeDialog(HOUR_PICKER);
					showDialog(MINUTE_PICKER);	
				}
			})
			.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					removeDialog(HOUR_PICKER);
					dialog.cancel();
				}
			});
			break;
		case	MINUTE_PICKER:
			minute=(String)minutes[0];//default to 00
			minuteValue=minuteValues[0];
			builder.setTitle("Choose Start Minute");
			builder.setCancelable(false);
			builder.setSingleChoiceItems(minutes, 0, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int item) {
					minute=(String) minutes[item];
					minuteValue=minuteValues[item];
					minute=String.valueOf(minute);
					android.util.Log.w("picker: ", minute);	
				}
			})
			.setPositiveButton("Set", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					minute=String.valueOf(minuteValue);
					android.util.Log.w("picker: ", minute);
					cv.put("start", hourValue+minuteValue);
					android.util.Log.w("cv: ", String.valueOf(hourValue+minuteValue));
					removeDialog(MINUTE_PICKER);
					showDialog(FHOUR_PICKER);
				}
			})
			.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					removeDialog(MINUTE_PICKER);
					dialog.cancel();
				}
			});
			break;
		case FHOUR_PICKER:
			hour=(String)hours[0];//default to 09:00
			hourValue=hourValues[0];
			builder.setTitle("Choose Finish Hour");
			builder.setCancelable(false);
			builder.setSingleChoiceItems(hours, 0, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int item) {
					hour=(String) hours[item];
					hourValue=hourValues[item];
					hour=String.valueOf(hourValue);
					android.util.Log.w("picker: ", hour);	
				}
			})
			.setPositiveButton("Set", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					hour=String.valueOf(hourValue);
					android.util.Log.w("picker: ", hour);
					removeDialog(FHOUR_PICKER);
					showDialog(FMINUTE_PICKER);	
				}
			})
			.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					removeDialog(FHOUR_PICKER);
					dialog.cancel();
				}
			});
			break;
		case FMINUTE_PICKER:
			minute=(String)minutes[0];//default to 00
			minuteValue=minuteValues[0];
			builder.setTitle("Choose Finish Minute");
			builder.setCancelable(false);
			builder.setSingleChoiceItems(minutes, 0, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int item) {
					minute=(String) minutes[item];
					minuteValue=minuteValues[item];
					minute=String.valueOf(minute);
					android.util.Log.w("picker: ", minute);	
				}
			})
			.setPositiveButton("Set", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					minute=String.valueOf(minuteValue);
					android.util.Log.w("picker: ", minute);
					cv.put("finish", hourValue+minuteValue);
					android.util.Log.w("cv: ", String.valueOf(hourValue+minuteValue));
					// validate data
					boolean valid = true;
					String s="Entry valid";
					if(!hasCapacity()) {
						s="Schedule Full!";
						valid = false;
					}
					if(isDayFull((String) cv.get("day"))){
						s=day + "s are full \n(Max 5 schedules per day)";
						valid = false;
					}
					int f=(Integer)cv.get("finish");
					int st=(Integer)cv.get("start");
					if( f <= st ) {	
						s="Finish time " + f + " is not greater than Start time " + st;
						valid=false;
					}
					if( isOverlap(cv) ) {
						s="This overlaps with exsisting schedule";
						valid=false;
					}
					if(valid==true){
						insertCV(cv);// commit to db
						android.util.Log.w("GUI","Schedule set");
						updateUI();
					}
					removeDialog(FMINUTE_PICKER);
					Toast.makeText(ScheduleActivity.this, s, Toast.LENGTH_SHORT).show();
				}
			})
			.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					removeDialog(FMINUTE_PICKER);
					dialog.cancel();
				}
			});
			break;
		case	DELETE_CONFIRM:
			builder.setTitle("Delete?");
			builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					String[] args={ deleteDay, String.valueOf(deleteStart), String.valueOf(deleteFinish)};
					db.delete("schedule","day=? AND start=? AND finish=?", args);
					android.util.Log.w("position: ", String.valueOf(pos));
					android.util.Log.w("Deleted", String.valueOf(pos));
				
					dialog.dismiss();
					updateUI();				
				}
			})
			.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			break;
		default:
			alert=null;
			break;
		}
		
		alert=builder.create();
		return alert;	
	}

	// insert content values into db
	private long insertCV(ContentValues cv) {
		long rowId;
		rowId=db.insert("schedule", "start", cv);
		if(rowId>0) {
			return rowId;// >0 if row inserted
		}else{
			throw new SQLException("Failed to insert row");
		}
	}

	// check for overlapping schedules
	private boolean isOverlap(ContentValues cv) {
		String d=cv.getAsString("day");
		String s=cv.getAsString("start");
		String f=cv.getAsString("finish");
		android.util.Log.w("cast", s);
		android.util.Log.w("cast", f);
		String[] selectionArgs={d, s, s, f, f};
		result = db.query("schedule", new String [] {"_id"},
				"day=? AND ((?>=start AND ?<=finish) OR (?>=start AND ?<=finish))", selectionArgs, null, null, null);
		if(result.getCount()>0) {
			return true;
		}
		return false;
	}
	
	// check capacity of schedule
	private boolean hasCapacity() {
		result = db.rawQuery("SELECT * FROM schedule", null);
		int count=result.getCount();
		if (count>=MAX_EVENTS){	
			return false;
		}
		return true;
	}
	
	// check limit to daily events in schedule
	private boolean isDayFull(String day) {
		String[] s={""};
		String[] columns={"day"};
		s[0]=day;
		result=db.query("schedule", columns, "day=?", s, null, null, null);
		if(result.getCount()>=MAX_DAILY_EVENTS){
			return true;
		}
		return false;
	}
	
	public void onConfigurationChanges(Configuration newConfig) {
		 
	}
}
